var express = require('express');
var router = express.Router();

const mysql_1 = require("mysql");
let connection = mysql_1.createConnection({
  host: '172.23.7.241',
  port: '3307',
  user: 'tendcloud',
  password: 'tendcloudpasswd',
  database: 'app_meta'
});
connection.connect();

//接收分页查询请求，必选参数：tableName，可选参数：start，rows
//http://localhost:3000/queryPage?tableName=TD_TAG
router.get('/queryPage/:tableName', function (req, res) {
  let tableName = 'data_transform_meta_' + req.params.tableName;
  let start = req.query.start || 0;
  let rows = req.query.rows || 10;
  connection.query('SELECT count(*) as total from ' + tableName, function (error, results, fields) {
    if (error)
      throw error;
    let total = results[0].total;
    connection.query('SELECT * from ' + tableName + ' limit ' + start + ',' + rows, function (error, results, fields) {
      if (error)
        throw error;
      console.log('query table ' + tableName + ', length: ', total);
      res.send({
        total: total,
        data: results,
        fields: fields
      });
    });
  });
});
//查询所有，必选参数：tableName,可选参数：filter
//http://localhost:3000/queryAll?tableName=TD_TAG&creator=bjadmin
router.get('/:tableName', function (req, res) {
  let tableName = 'data_transform_meta_' + req.params.tableName;
  let whereClause = " where 1 = 1";
  for (let key in req.query) {
    if (key != "tableName" && key === 'domain') {
      whereClause += " and " + key + " = '" + req.query[key] + "'";
    }
  }
  connection.query('SELECT * from ' + tableName + whereClause, function (error, results, fields) {
    if (error)
      throw error;
    console.log('query table ' + tableName + ', length: ', results.length);
    const contentList = results.map(item => {
      return JSON.parse(item.DATA);
    });
    res.send({
      code: 200,
      message: '成功',
      src: 'express',
      data: {
        total: results.length,
        content: contentList,
      }
    });
  });
});
//查询所有，必选参数：tableName,可选参数：filter
//http://localhost:3000/queryAll?tableName=TD_TAG&creator=bjadmin
router.get('/queryOne/:tableName/:id', function (req, res) {
  let tableName = 'data_transform_meta_' + req.params.tableName;
  let whereClause = " where 1 = 1 and id = " + req.params.id;
  connection.query('SELECT * from ' + tableName + whereClause, function (error, results, fields) {
    if (error)
      throw error;
    console.log('query table ' + tableName + ', length: ', results.length);
    if (results.length == 1) {
      res.send(results[0]);
    }
    else {
      res.send({
        total: results.length,
        data: results,
        fields: fields
      });
    }
  });
});

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;